<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 14:28
 */

namespace App\Http\Controllers\Index;

use App\Model\ClassifyModel;
use App\Model\CommentModel;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\WebController;
use App\Model\ArticleModel;
use App\Model\PhotoModel;
use Symfony\Component\HttpFoundation\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class IndexController extends WebController
{
    public function index(Request $request)
    {
        $searchField = $request->only(['content']);
        $searchField = array_filter($searchField, 'strlen');
        if (empty($searchField)) {
            $data['list'] = ArticleModel::selectRaw('xf_userinfo.url,xf_article.article_id,xf_article.content,xf_article.title,xf_article.add_time')->leftJoin('xf_userinfo', 'xf_userinfo.user_id', '=', 'xf_article.user_id')->orderBy('xf_article.add_time', 'desc')->paginate(10);
        } else {
            $data['list'] = ArticleModel::selectRaw('xf_userinfo.url,xf_article.article_id,xf_article.content,xf_article.title,xf_article.add_time')->leftJoin('xf_userinfo', 'xf_userinfo.user_id', '=', 'xf_article.user_id')
                ->orderBy('xf_article.add_time', 'desc')
                ->where('title', 'like', '%' . $searchField['content'] . '%')
                ->paginate(10);
            $data['search']=$searchField;
        }
        return view('index/index', $data);
    }

    public function create()
    {
        // 进行分页数据查询
        $data['classify']=ClassifyModel::get();
        return view('index/add',$data);
    }

    public function store(Request $request)
    {
        $content = $request->all();
        if(!isset($content['content'])){
            return back()->with('success', '请添写文章内容！');
        }
        $userId = ['user_id' => session('userid')];
        $data = array_merge($userId,$content);
        DB::beginTransaction();
        try {
            $id = ArticleModel::create($data);
            DB::commit();
            if ($id) {
                return back()->with('success', '添加文章成功！');
            } else {
                return back()->with('success', '添加文章失败！');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info("添加文章失败！" . $e->getTraceAsString());
        }

    }
}